package com.exp.bookhouse.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.exp.bookhouse.pojo.Order;
import com.exp.bookhouse.service.OrderService;
import com.exp.bookhouse.util.AmountUtil;
import com.exp.bookhouse.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Api(value = "订单管理接口",tags = "管理员管理订单操作")
@Controller
@RequestMapping("/admin")
public class OrderControllerAdmin {

    @Autowired
    private OrderService orderService;

    @ApiOperation(value = "查询订单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "p", value = "页数", required = false, dataType = "Int"),
            @ApiImplicitParam(paramType = "query", name = "s", value = "显示记录数", required = false, dataType = "Int")
    })
    @GetMapping("/toOrder")
    public String toOrder(@RequestParam(value = "p", required = false, defaultValue = "1")Integer page,
                             @RequestParam(value = "s", required = false, defaultValue = "5")Integer size,
                             Model model){
        IPage<Order> iPage = orderService.queryOrderByPage(page,size);
        model.addAttribute("iPage",iPage);
        return "order";
    }


    @ApiOperation(value = "按名称查询订单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", name = "userName", value = "用户名称", required = true, dataType = "String"),
    })
    @PostMapping("/searchOrder")
    public String searchOder(@RequestParam("userName")String userName,Model model){
        List<Order> iPage = orderService.getOrderByName(userName);
        model.addAttribute("iPage",iPage);
        return "orderSearchResult";
    }


    @ApiOperation(value = "查询订单和细节")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "订单id", required = true, dataType = "Long")
    })
    @GetMapping("/queryOrderDetail/{id}")
    public String queryOrderDetail(@PathVariable("id")Long id, Model model){
        Order order = orderService.queryOrderDetail(id);
        model.addAttribute("order",order);
        return "orderDetail";
    }


    @ApiOperation(value = "导出订单列表")
    @RequestMapping("/exportOrder")
//    @ResponseExcel({"orderNum", "userName", "userPhone","userAddress","amount","createTime","updateTime"})
    @ResponseBody
    public int exportOrder() {
        List<Order> orders = new ArrayList<>();
        orders = orderService.queryAllOrder();
        return exportExcelPaper(orders);
    }
    public int exportExcelPaper(List<Order> orders) {
        // 标题
        String[] title = { "订单号", "买家", "买家电话", "买家地址", "总金额", "订单创建时间", "订单完成时间"};
        // 创建一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建一个工作表sheet
        HSSFSheet sheet = workbook.createSheet();
        // 设置列宽
        setColumnWidth(sheet, 8);
        // 创建第一行
        HSSFRow row = sheet.createRow(0);
        // 创建一个单元格
        HSSFCell cell = null;
        // 创建表头
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            // 设置样式
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            // 设置字体
            HSSFFont font = workbook.createFont();
            font.setFontName("宋体");
            // font.setFontHeight((short)12);
            font.setFontHeightInPoints((short) 13);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);

            cell.setCellValue(title[i]);
        }
        // 从第二行开始追加数据
        for (int i = 1; i < (orders.size() + 1); i++) {
            // 创建第i行
            HSSFRow nextRow = sheet.createRow(i);
            for (int j = 0; j < 7; j++) {
                Order order = orders.get(i-1);
                HSSFCell cell2 = nextRow.createCell(j);
                if (j == 0) {
                    cell2.setCellValue(order.getOrderNum());
                }
                if (j == 1) {
                    cell2.setCellValue(order.getUserName());
                }
                if (j == 2) {
                    cell2.setCellValue(order.getUserPhone());
                }
                if (j == 3) {
                    cell2.setCellValue(order.getUserAddress());
                }
                if (j == 4) {
                    String str = AmountUtil.changeF2Y(order.getAmount());
                    cell2.setCellValue(str);
                }
                if (j == 5) {
                    String date = DateUtil.formatTimesTampDate(order.getCreateTime());
                    cell2.setCellValue(date);
                }
                if (j == 6) {
                    String date = DateUtil.formatTimesTampDate(order.getUpdateTime());
                    cell2.setCellValue(date);
                }
            }
        }

        // 临时创建一个文件
        File file = new File("E:/order.xls");
        try {
            file.createNewFile();
            // 打开文件流
            FileOutputStream outputStream = FileUtils.openOutputStream(file);
            workbook.write(outputStream);
            outputStream.close();
            return 1;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return -1;
    }
    // 设置列宽()
    private static void setColumnWidth(HSSFSheet sheet, int colNum) {
        for (int i = 0; i < colNum; i++) {
            int v = 0;
            v = Math.round(Float.parseFloat("15.0") * 37F);
            v = Math.round(Float.parseFloat("20.0") * 267.5F);
            sheet.setColumnWidth(i, v);
        }
    }

    @ApiOperation(value = "下载订单列表")
    @PostMapping("/downloadOrder")
    public void downloadOrder(HttpServletResponse response,Model model) {
        //待下载文件名
        String fileName = "order.xls";
        //设置为png格式的文件
        response.setHeader("content-type", "application/x-xls");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        byte[] buff = new byte[1024];
        //创建缓冲输入流
        BufferedInputStream bis = null;
        OutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();

            //这个路径为待下载文件的路径
            bis = new BufferedInputStream(new FileInputStream(new File("E:/" + fileName )));
            int read = bis.read(buff);

            //通过while循环写入到指定了的文件夹中
            while (read != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                read = bis.read(buff);
            }
        } catch ( IOException e ) {
            e.printStackTrace();
            //出现异常返回给页面失败的信息
            model.addAttribute("result","下载失败");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String path = "E:/" + fileName;//临时创建的表格路径
        File file = new File(path);
        if(file.exists()){//文件存在删除文件
            file.delete();
        }
    }

}
